package com.task.src.util;

import com.google.gson.internal.$Gson$Preconditions;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileUtil {

    public static String uploadFile(MultipartFile multipartFile){
        String uploadPath="";
        String fileName=multipartFile.getOriginalFilename();
        uploadPath="D:\\qtProject\\Task\\src\\main\\resources\\static\\img\\user\\"+fileName;
        File tempFile = new File(uploadPath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        try {
            multipartFile.transferTo(tempFile);
            return "success";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }



    public static void downloadLocal(HttpServletResponse response,String path) throws FileNotFoundException {
        // 下载本地文件
        int i = path.indexOf(".");
        String s= path.substring(i);
        String fileName = "LoadDown"+s; // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream(path);// 文件的存放路径
        // 设置输出的格式
        response.reset();
//        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
